package com.caird.pmp.iot.handler.impl;


import com.caird.pmp.iot.entity.DeviceShadow;
import com.caird.pmp.iot.handler.HandlerBase;
import com.caird.pmp.iot.message.IMessage;
import com.caird.pmp.iot.message.MessageFactory;
import com.caird.pmp.iot.message.impl.DeviceMessage0100;
import com.caird.pmp.iot.message.impl.ServerMessage8100;
import com.caird.pmp.iot.server.BbChannelManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller
public class Handler0100 extends HandlerBase {

    @Override
    public boolean handle(Channel channel, IMessage message) {

        DeviceMessage0100 dm = (DeviceMessage0100)message;

        ServerMessage8100 sm = (ServerMessage8100) MessageFactory.make("8100");
        sm.setSimNo(dm.getSimNo());
        sm.setFlowNo(BbChannelManager.getFlowNo(channel));
        sm.setResFlowNo(dm.getFlowNo());

        if (cacheService.isSimNoExist(dm.getSimNo()))
            sm.setResult((byte)0);
        else
            sm.setResult((byte)4);
        sm.setAuth(new StringBuffer(dm.getSimNo()).reverse().toString());

        //应答
        writeAndFlush(channel, sm.encode());

        //保存注册信息
        if (0 == sm.getResult()) {
            DeviceShadow shadow = getShadow(dm.getSimNo());
            shadow.setRegTime(new Date());
            shadow.setRegCount(null == shadow.getRegCount() ? 1 : shadow.getRegCount() + 1);
            shadow.setMaker(dm.getMaker());
            shadow.setModel(dm.getModel());
            shadow.setSn(dm.getSn());
            setShadow(dm.getSimNo(), shadow);
        }

        return true;
    }
}
